﻿// 项目：	Guan.CMS.Domain - Guan.CMS
// 文件名：	AddOrUpdateProductCategtoryHandler.cs
// 
// 修改时间：2013-03-15 21:24
// 修改人：	Cooclsee

using Guan.CMS.CommandProcessor.Command;
using Guan.CMS.Data.Infrastructure;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.ProductCategory;

namespace Guan.CMS.Domain.Handlers.ProductCategory
{
    public class AddOrUpdateProductCategtoryHandler : ICommandHandler<AddOrUpdateProductCategoryCommand>
    {
        private readonly IProductCategoryRepository _productCategoryRepository;
        private readonly IUnitOfWork _unitOfWork;
        public AddOrUpdateProductCategtoryHandler(IProductCategoryRepository productCategoryRepository, IUnitOfWork unitOfWork)
        {
            this._productCategoryRepository = productCategoryRepository;
            this._unitOfWork = unitOfWork;
        }

        public ICommandResult Execute(AddOrUpdateProductCategoryCommand command)
        {
            var isAdd = command.Id == 0;
            Model.Entities.ProductCategory model = null;
            if (isAdd)
            {
                model = new Model.Entities.ProductCategory{IsPublished = true};
            }
            else
            {
                model = _productCategoryRepository.GetById(command.Id);
            }
            model.Name = command.Name;
            model.ParentId = command.ParentId;
            if (isAdd)
            {
                _productCategoryRepository.Add(model);
            }
            else
            {
                _productCategoryRepository.Update(model);
            }
            _unitOfWork.Commit();
            return new CommandResult(true);
        }
    }
}